package com.mxpio.erp.equipment.service.impl;

import com.mxpio.erp.common.equipment.entity.EquipmentKnowledgeTag;
import com.mxpio.erp.common.equipment.entity.EquipmentTagRecord;
import com.mxpio.erp.common.equipment.service.EquipmentKnowledgeTagService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 知识库-标签Service业务层处理
 *
 * @author Cheng
 * @date 2023-12-23
 */
@Service
public class EquipmentKnowledgeTagServiceImpl extends BaseServiceImpl<EquipmentKnowledgeTag> implements EquipmentKnowledgeTagService {

    @Override
    @Transactional(readOnly = false)
    public void changeStatus(EquipmentTagRecord equipmentTagRecord) {
        List<String> idList = Arrays.asList(equipmentTagRecord.getTagId().split(","));
        List<EquipmentKnowledgeTag> list = JpaUtil.linq(EquipmentKnowledgeTag.class).in("id", idList).list();
        ArrayList<EquipmentTagRecord> tagRecords = new ArrayList<>();
        for (EquipmentKnowledgeTag tag : list) {
            if(equipmentTagRecord.getAfterStatus().equals(tag.getTagStatus())){
                continue;
            }
            //记录变更日志
            EquipmentTagRecord tagRecord = new EquipmentTagRecord();
            tagRecord.setTagId(tag.getId());
            tagRecord.setTagCode(tag.getTagCode());
            tagRecord.setBeforeStatus(tag.getTagStatus());
            tagRecord.setAfterStatus(equipmentTagRecord.getAfterStatus());
            tagRecord.setChangeReason(equipmentTagRecord.getChangeReason());
            tagRecord.setRemark(equipmentTagRecord.getRemark());
            tagRecords.add(tagRecord);

            //更新状态
            tag.setTagStatus(equipmentTagRecord.getAfterStatus());
            JpaUtil.update(tag);
        }
        JpaUtil.save(tagRecords);
    }
}
